package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MakeFriendManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private RecommendUserService recommendUserService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private QuestionService questionService;

    @Reference
    private VisitorService visitorService;

    @Reference
    private UserLocationService userLocationService;

    @Reference
    private FriendService friendService;

    //今日佳人
    public RecommendUserVo findTodayBest() {
        //1. 获取登录用户
        Long userId = UserHolder.get().getId();

        //2. 根据用户id查询它的今日佳人
        RecommendUser recommendUser = recommendUserService.findTodayBest(userId);

        //3. 判断上面的这个是否为空,如果是空,手动推荐一个(企业中是没有这步骤的)
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);
        }

        //4. 组装返回vo
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfoService.findByUserId(recommendUser.getUserId()));
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return recommendUserVo;
    }

    //推荐用户列表
    public PageBeanVo findRecommendUserList(Integer pageNum, Integer pageSize) {
        //1. 获取登录用户
        Long userId = UserHolder.get().getId();

        //2. 根据用户id分页查询它的推荐用户列表
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserList(userId, pageNum, pageSize);

        //3. 处理返回结果
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollectionUtil.isEmpty(recommendUserList)) {
            //模拟数据
            for (Integer i = 2; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(i.longValue());
                recommendUser.setScore(98D);
                recommendUserList.add(recommendUser);
            }
        }

        //4. RecommendUser------>RecommendUserVo
        List<RecommendUserVo> recommendUserVoList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            recommendUserVo.setUserInfo(userInfoService.findByUserId(recommendUser.getUserId()));
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());
            recommendUserVoList.add(recommendUserVo);
        }

        pageBeanVo.setItems(recommendUserVoList);
        return pageBeanVo;
    }

    //佳人详情
    public RecommendUserVo findRecommendUserInfo(Long recommendUserId) {
        //1. 查询佳人详情
        UserInfo userInfo = userInfoService.findByUserId(recommendUserId);

        //2. 调用service根据两人id查询缘分值
        Long userId = UserHolder.get().getId();
        RecommendUser recommendUser = recommendUserService.findRecommendUser(userId, recommendUserId);

        //3. 设置缘分值
        Long fateValue = 98L;
        if (recommendUser != null) {
            fateValue = recommendUser.getScore().longValue();
        }

        //4. 组装返回vo
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(fateValue);

        return recommendUserVo;
    }

    //聊一下(查询佳人设置的陌生人问题)
    public String findStrangerQuestion(Long userId) {
        //1. 调用service根据userId查询问题
        Question question = questionService.findByUserId(userId);

        //2. 如果查不到,返回默认值
        if (question == null) {
            return new SettingVo().getStrangerQuestion();
        }

        //3. 返回正常结果
        return question.getStrangerQuestion();
    }

    //谁看过我
    public List<VisitorVo> findVisitorList() {
        //1. 当前用户
        Long userId = UserHolder.get().getId();

        //2. 根据用户id查询当前用户最后一次访问时间
        String time = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        if (StringUtils.isEmpty(time)) {
            //设置为当前时间
            time = System.currentTimeMillis() + "";
        }

        //3. 根据userId和time去调用service查询
        List<Visitor> visitorList = visitorService.findVisitorList(userId, time);
        List<VisitorVo> visitorVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(visitorList)) {
            for (Visitor visitor : visitorList) {
                //visitor----VisitorVo
                //1.创建vo
                VisitorVo visitorVo = new VisitorVo();

                //2. 赋值
                visitorVo.setUserInfo(userInfoService.findByUserId(visitor.getVisitorUserId()));
                visitorVo.setFateValue(99L);

                //3. 放入临时集合
                visitorVoList.add(visitorVo);

            }
        }

        //4. 更新一下最后访问时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        return visitorVoList;
    }

    //上报地理位置
    public void saveUserLocation(Double longitude, Double latitude, String address) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 保存地理位置
        userLocationService.saveUserLocation(userId, longitude, latitude, address);
    }

    //查询附近的人
    public List<NearUserVo> findNearUserList(String gender, Long distance) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 根据登录用户位置和指定长度寻找附近的人
        List<Long> userIdList = userLocationService.findNearUserList(userId, distance);

        //3. 如果没查到附近的人,直接返回空集合
        if (CollectionUtil.isEmpty(userIdList)) {
            return new ArrayList<NearUserVo>();
        }

        List<NearUserVo> nearUserVoList = new ArrayList<>();

        //4. 如果查到了
        for (Long uid : userIdList) {
            //4-1. 先排除自己
            if (uid == userId) {
                continue;
            }

            //4-2.筛选性别(man )
            UserInfo userInfo = userInfoService.findByUserId(uid);
            if (!StringUtils.equals(userInfo.getGender(), gender)) {
                continue;
            }

            //4-3 将符合条件的用户组装成返回对象
            NearUserVo nearUserVo = new NearUserVo();
            nearUserVo.setUserId(uid);
            nearUserVo.setAvatar(userInfo.getAvatar());
            nearUserVo.setNickname(userInfo.getNickname());
            nearUserVoList.add(nearUserVo);

        }

        return nearUserVoList;
    }

    //打招呼
    public void replyStrangerQuestion(Integer strangerId, String reply) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();
        //2. 根据id查询登录用户信息
        String nickname = userInfoService.findByUserId(userId).getNickname();
        //3. 查询佳人的陌生人问题
        String strangerQuestion = new SettingVo().getStrangerQuestion();
        Question question = questionService.findByUserId(strangerId.longValue());
        if (question != null) {
            strangerQuestion = question.getStrangerQuestion();
        }
        //4. 组装json
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId + "");
        map.put("nickname", nickname);
        map.put("strangerQuestion", strangerQuestion);
        map.put("reply", reply);
        String json = JSON.toJSONString(map);
        System.out.println("发送的信息是:" + json);

        //5. 调用环信的api发送
        huanXinTemplate.sendMsg(strangerId + "", json);
    }

    //添加好友(聊一下)
    public void saveFriend(Long friendId) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 调用service保存用户关系
        friendService.save(userId, friendId);

        //3. 调用环信保存用户关系
        huanXinTemplate.addContacts(userId, friendId);
    }

    //查询我的好友
    public PageBeanVo findMyFriend(Integer pageNum, Integer pageSize) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 根据id调用service分页查询好友列表
        PageBeanVo pageBeanVo = friendService.findFriendByUserId(userId,pageNum,pageSize);

        //3. 处理结果
        List<Friend> friendList  = (List<Friend>) pageBeanVo.getItems();
        List<ContactVo> contactVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(friendList)){
            for (Friend friend : friendList) {
                Long friendId = friend.getFriendId();//好友id
                UserInfo userInfo = userInfoService.findByUserId(friendId);

                ContactVo contactVo = new ContactVo();
                contactVo.setUserInfo(userInfo);
                contactVo.setUserId(friendId+"");

                contactVoList.add(contactVo);

            }
        }

        pageBeanVo.setItems(contactVoList);
        return pageBeanVo;
    }
}
